package org.linuxgears.BouncingBall.model.context;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

public class ConditionalContextMutator<T> implements ContextMutator<T> {
    private HashMap<Trigger<T>, Collection<ContextMutator<T>>> xtcMutationMap;

    public Collection<ContextMutator<T>> on(Trigger<T> trigger) {
    	if (trigger == null) return null;
    	
    	Collection<ContextMutator<T>> bcmList;
        if (xtcMutationMap == null) {
        	xtcMutationMap = new HashMap<Trigger<T>, Collection<ContextMutator<T>>>();
        }
        
    	if (! xtcMutationMap.containsKey(trigger)) {
    		bcmList = new ArrayList<ContextMutator<T>>();
    		xtcMutationMap.put(trigger, bcmList);
    	} else {
    		bcmList = xtcMutationMap.get(trigger);
    	}
    	
    	return bcmList;
    }
    
	@Override 
    public void mutate(T xtc) {
    	for (Trigger<T> trigger: xtcMutationMap.keySet()) {
    		if (trigger.triggered(xtc)) {
    			for (ContextMutator<T> mutator: xtcMutationMap.get(trigger)) {
    				mutator.mutate(xtc);
    			}
    		}
    	}
    }

}
